#!/usr/bin/python2.4


import itertools
import operator

import flags
import host as host_module
import rpc_stubs
import sql_query
import utils


flags.add_option('--log-hosts', '--lh', action='store_true')


class MachineManager(object):

  def __init__(self, **get_hosts_args):
    self.get_hosts_args = get_hosts_args

  def __repr__(self):
    return '%s(%s)' % (type(self).__name__,
                       ', '.join('%s=%r' % kv
                                 for kv in self.get_hosts_args.iteritems()))

  def __getattr__(self, name):
    try:
      return self.get_hosts_args[name]
    except KeyError:
      raise AttributeError('%r object has no attribute %r' % (
                           type(self).__name__, name))

  def setup(self):
    pass

  def get_hosts_filter_data(self, **overrides):
    filter_data = dict(self.get_hosts_args)
    utils.update_dict(filter_data, overrides)
    return filter_data

  def get_hosts(self, **filter_data):
    filter_data = self.get_hosts_filter_data(**filter_data)
    filter_data.setdefault('log_results', flags.get_option('log_hosts'))
    hosts = rpc_stubs.afe.get_hosts(**filter_data)

    pending_host_queue_entries = rpc_stubs.afe.get_host_queue_entries(
        complete=False,
        host__hostname__in=[host['hostname'] for host in hosts])
    pending_special_tasks = rpc_stubs.afe.get_special_tasks(
        is_complete=False,
        host__hostname__in=[host['hostname'] for host in hosts])
    job_pending_hostnames_set = set(
        entry['host']['hostname']
        for entry in itertools.chain(pending_host_queue_entries,
                                     pending_special_tasks))
    hosts = [host_module.Host(
                 host, idle=host['hostname'] not in job_pending_hostnames_set)
             for host in hosts]

    hosts.sort(key=operator.attrgetter('sort_key'))

    return hosts

  def get_sql_hosts(self, **filter_data):
    filter_data = self.get_hosts_filter_data(**filter_data)
    filter_data.setdefault('log_results', flags.get_option('log_hosts'))
    hosts = sql_query.sql.get_hosts(**filter_data)
    hosts.sort(key=operator.attrgetter('sort_key'))
    return hosts

  def pformat(self):
    return ' '.join('%s:%r' % kv
                    for kv in self.get_hosts_args.iteritems())


utils.import_site(globals())
